//获取应用实例
var app = getApp();

var FormCheckRule = {
    idCardRule1: /^[0-9]{14}([0-9]|X|x)$/,
    idCardRule2: /^[0-9]{17}([0-9]|X|x)$/,
    nameRule: /^[^ ]{2,60}$/,
    telRule: /^[1]{1}[0-9]{10}$/,
    carNbrSufRule: /^[a-zA-Z]{1}[a-zA-Z0-9]{4}[a-zA-Z0-9\u4E00-\u9FA5]{1,2}$/,

    cardNbrNullMessage:"请输入受理编号！",
    cardNbrErrorMessage:"请输入正确的受理编号！",
    cardErrorMessage:"请扫描正确的受理编号！",
    cardPlateNullMessage:"请输入车牌号码！",
    cardPlateErrorMessage:"请输入正确的车牌号码！",
    urgentApplicantNullMessage:"请输入车主名称！",
    urgentApplicantErrorMessage:"请输入正确的申请人姓名！",
    contactNameNullMessage:"请输入收件人姓名！",
    contactNameErrorMessage:"请输入正确的收件人姓名！",

    cellNumNullMessage:"请输入收件人电话！",
    cellNumErrorMessage:"请输入正确的收件人电话！",

    areaNameNullMessage:"请选择所在地区！",
    streetNullMessage:"请输入详细地址！",
    streetMinNullMessage:"详细地址不能小于5个字符！",
    checkService:"请阅读并同意《机动车牌邮寄服务协议》",
    typeSelection:"请选择车辆类型！"
};

Page({
    data: {
        showView: false, //车牌前缀
        showViewList: false, //车辆列表
        isCanScroll:true,
        userCellId: 0,
        cardNbrIconType: "",
        cardFixIconType: "",
        cardApplicant: "",
        recipientNameType: "",
        contactNumberType: "",

        //省，市，区选择
        area:"请选择所在地区",
        areaStyle:"color: #B2B2B2;font-size:34rpx",
        typeStyle:"color: #B2B2B2;font-size:34rpx",
        cardNbrStyle:"",
        isNoticeShow:false,  //服务协议说明
        needInvoice:0,  //是否勾选

        //输入框默认值
        cardNbr:"",   //受理编号
        userCellName: "粤",  //车牌前缀
        cardFix: "", //车牌号码
        recipientName: "", //收件人姓名
        typeSelectionText: "请选择车辆类型",
        isShowFootNav:true,
        isFromScanCode:false,
        isSwitchChecked:false,
        isHandleSuccess:false,//是否受理成功
        num: 0
    },
    onLoad: function (options) {
        // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
        app.globalData.channelId = decodeURIComponent(options.scene) != 'undefined'?
                            decodeURIComponent(options.scene) : app.globalData.channelId ? 
                            app.globalData.channelId:'';
        console.log("channelId",app.globalData.channelId);

        app.initAddress();
        var page =  app.getStorageSync(app.globalData.cacheData);
        if(page){
            this.setData({
                cardNbr: page.cardNbr,
                userCellName: page.userCellName,
                typeSelectionText: page.typeSelectionText,
                typeSelectionCode: page.typeSelectionCode,
                applicant: page.applicant,
                cardFix: page.cardFix,
                recipientName: page.recipientName,
                contactNumber: page.contactNumber,
                isSwitchChecked: page.isSwitchChecked,
                area: page.area,
                "address.street": page.address?page.address.street:"",
                "needInvoice":page.needInvoice
            });
            if(page.isSwitchChecked){
                if(page.address != null){
                    this.setData({
                        "area":page.area,
                        "address.street":page.address.street,
                        "address.provinceId":page.address.provinceId,
                        "address.cityId":page.address.cityId,
                        "address.countyId":page.address.countyId,
                        "address.provinceName":page.address.provinceName,
                        "address.cityName":page.address.cityName,
                        "address.countyName":page.address.countyName,
                        "address.cellNum":page.address.cellNum,
                        "address.contactName":page.address.contactName
                    });
                }
                if ("请选择所在地区"==page.area){
                    this.setData({"areaStyle": "color: #B2B2B2;font-size:34rpx",});
                }else{
                    this.setData({"areaStyle": "color: #1a1a1a;font-size:34rpx",});
                }
            }else{
                this.setData({
                    "contactNumber":"",
                    "recipientName":"",
                    "area":"请选择所在地区",
                    "areaStyle":"color: #B2B2B2;font-size:34rpx",
                    "address.street":"",
                    "address.provinceId":"",
                    "address.cityId":"",
                    "address.countyId":"",
                    "address.provinceName":"",
                    "address.cityName":"",
                    "address.countyName":"",
                    "address.cellNum":"",
                    "address.contactName":""
                });
            }
        }
    },
    //分享功能
    onShareAppMessage:function () {
        return {
            title: '机动车牌邮寄服务',
            desc: '机动车牌邮寄服务!',
            path: '/pages/handle/handle?scene='+app.globalData.channelId
        }
    },
    onHide:function () {
        app.setStorageSync(app.globalData.cacheData,this.data);
    },
    onShow:function () {
        var pageObj = this;
        app.authAjax();
        var isFromScanCode = pageObj.data.isFromScanCode;
        var page = app.getStorageSync(app.globalData.cacheData);
        if(!isFromScanCode){
            if( page.cardNbr==null){
                pageObj.setData({cardNbr:null});
            }
            if( page.applicant==null){
                pageObj.setData({applicant:null});
            }
            pageObj.setData({
                num: page.num
            });
        }
        pageObj.setData({isFromScanCode: false});
        if(page.isHandleSuccess&&!page.isSwitchChecked){//受理成功且不记住地址
            pageObj.setData({
                "contactNumber":"",
                "recipientName":"",
                "area":"请选择所在地区",
                "areaStyle":"color: #B2B2B2;font-size:34rpx",
                "address.street":"",
                "address.provinceId":"",
                "address.cityId":"",
                "address.countyId":"",
                "address.provinceName":"",
                "address.cityName":"",
                "address.countyName":"",
                "address.cellNum":"",
                "address.contactName":""
            });
        }
    },

    //底部切换页面方法
    toUrl:function (e) {
        var url = e.currentTarget.dataset.url;
        if(url!='/pages/handle/handle'){
            app.setStorageSync(app.globalData.cacheData,this.data);
            if(url == ''){
                var res = {
                    appid:app.globalData.appid,
                    path: app.globalData.path,
                    envVersion: app.globalData.envVersion
                }
                app.crossToUrl(res)
            }else {
                app.redirectTo({url: url+'?scene='+app.globalData.channelId});
            }
        }
    },

    //是否记住地址
    switchChange: function (e){
        this.setData({isSwitchChecked: e.detail.value});
    },

    //确认提交按钮
    formSubmit:function(e){
        var formData = e.detail.value;
        var cardNbr = formData.cardNbr;
        var cardFix = formData.cardFix;
        var cardApplicant = formData.cardApplicant;
        var recipientName = formData.recipientName;
        var cardNumber = formData.cardNumber;
        var street = formData['address.street'];
        var provinceId = formData['address.provinceId'];
        var needInvoice = formData.needInvoice;
        var pageObj = this;
        var flag = app.check([
            {
                value: cardNbr,
                errorFocusName:"cardNbr",
                errorScrollIntoViewName:"handleView",
                fn: function(value){
                    if(value == ''){
                        app.errorToast(FormCheckRule.cardNbrNullMessage);
                        return false;
                    }else if(value.length > 1){
                        return true;
                    }else {
                        app.errorToast(FormCheckRule.cardNbrErrorMessage);
                    }
                }
            },

            {
                value: cardApplicant,
                errorFocusName:"applicant",
                errorScrollIntoViewName:"handleView",
                fn: function (value) {
                    if(value == ''){
                        app.errorToast(FormCheckRule.urgentApplicantNullMessage);
                    }else if(FormCheckRule.nameRule.test(value)){
                        return true;
                    }else {
                        app.errorToast(FormCheckRule.urgentApplicantErrorMessage);
                    }
                }
            }, {
                value: recipientName,
                errorFocusName:"recipientName",
                errorScrollIntoViewName:"cardApplicantView",
                fn: function (value) {
                    if(value == ''){
                        app.errorToast(FormCheckRule.contactNameNullMessage);
                    }else if(FormCheckRule.nameRule.test(value)){
                        return true;
                    }else {
                        app.errorToast(FormCheckRule.contactNameErrorMessage);
                    }
                }
            }, {
                value: cardNumber,
                errorFocusName:"contactNumber",
                errorScrollIntoViewName:"recipientNameView",
                fn: function(value){
                    if(value == ''){
                        app.errorToast(FormCheckRule.cellNumNullMessage);
                    }else if(FormCheckRule.telRule.test(value)){
                        return true;
                    }else {
                        app.errorToast(FormCheckRule.cellNumErrorMessage);
                    }
                }
            }, {
                value: provinceId,
                errorFocusName:"provinceId",
                errorScrollIntoViewName:"cardNumberView",
                rule: app.globalData.Rule.required,
                fn: function (value) {
                    if(value!=''){
                        return true;
                    }else{
                        app.errorToast(FormCheckRule.areaNameNullMessage);
                        return false
                    }
                }
            }, {
                value: street,
                errorFocusName:"street",
                errorScrollIntoViewName:"areaView",
                fn: function(value){
                    if(value ==''){
                        app.errorToast(FormCheckRule.streetNullMessage);
                    }else if(value.length<5) {
                        app.errorToast(FormCheckRule.streetMinNullMessage);
                    }else {
                        return true;
                    }
                }
            }
        ]);

        if (!flag) {
            return false;
        }
        if(needInvoice==0){
            app.errorToast(FormCheckRule.checkService);
            return false;
        }
        if(!app.globalData.isAuthSuccess){
            app.toastAuthFailModal();
            return false;
        }
        var postData = formData;
        var res = this.data;
        postData['address.fullAddr'] = formData['address.provinceName']+formData['address.cityName']+formData['address.countyName']+street;
        postData['carNbr'] = res.cardFix?res.userCellName+res.cardFix:'';
        postData['acceptNbr'] = res.cardNbr;
        postData['name'] = res.applicant;
        postData['address.cellNum'] = formData.cardNumber;
        postData['address.contactName'] = formData.recipientName;
        var opt = {
            url: app.globalData.host+"/wx/cn/handling.ajax",
            data: postData,
            sucFn:function (result) {
                postData['serviceFee_cn'] = result.body.serviceFee;  //服务费
                postData['totalChargeFee_cn'] = result.body.totalChargeFee; //总费用
                postData['totalFee_cn'] = result.body.totalFee;
                postData['isLocal'] = result.body.local;
                postData['userCellName'] = res.userCellName;
                postData['cardFix'] = res.cardFix;
                app.setStorageSync(app.globalData.cacheOrderPay, postData);
                app.navigateTo({url:'../payment/payment'})
            }
        };
        app.ajax(opt);
    },
    //说明内容
    agreeTap:function (e) {
        app.navigateTo({url: '../notice/notice'});
    },
    //隐藏说明内容
    noticeKnowTap:function (e) {
        this.setData({
            isNoticeShow:false,
            isShowFootNav: true
        });
    },
    areaTap:function (e) {
        this.setData({
            isAddressShow: true,
            isShowFootNav: false
        });
    },

    //条形码
    bindViewTap: function() {
        var that = this;
        var path= /^[0-9a-zA-Z]*$/g;
        wx.scanCode({
            // onlyFromCamera: true,
            success: function(res){
                if(path.test(res.result)){
                    that.setData({
                        cardNbr: res.result,
                        isFromScanCode:true
                    });
                }else {
                    that.setData({
                        isFromScanCode:true
                    });
                    app.errorToast(FormCheckRule.cardErrorMessage);
                }
            }
        })
    },
    //车牌前缀
    userListAction:function(e){
        this.setData({
            userCellName: e.target.dataset.name,
            showView: false,
            isShowFootNav: true
        })
    },

    //点击车牌前缀
    provinceName: function(e){
        this.setData({
            showView: true,
            isShowFootNav:false
        })
    },

    //输入框公用方法
    infoInput: function(e){
        var id = e.currentTarget.id,
            value = e.detail.value.replace(/(^\s*)|(\s*$)/g,"");

        if(id == "cardNbr"){ //受理编号
            var pattern = /([^A-Za-z0-9]|\s)*/g,
                that = this;
            setTimeout(function(){
                value = value.replace(pattern, '');
                that.setData({"cardNbr": value});
            },0);
            if(value==''){
                this.setData({acceptanceIconType: "success"});
            }else if(value.length==1){
                this.setData({acceptanceIconType: "error"});
            }else {
                this.setData({acceptanceIconType: "success"});
            }
        }else if(id == "applicant"){
            this.setData({applicant: value});
            if(value==''){
                this.setData({cardNameIconType: "success"});
            }else if(FormCheckRule.nameRule.test(value)){
                this.setData({cardNameIconType: "success"});
            } else if(value.length>0){
                this.setData({cardNameIconType: "error"});
            }else {
                this.setData({
                    cardNameIconType: "",
                    applicant: value
                });
            }
        }else if(id == "recipientName"){
            this.setData({recipientName: value});
            if(value==''){
                this.setData({recipientNameIconType: "success"});
            }else if (FormCheckRule.nameRule.test(value)) {
                this.setData({recipientNameIconType: "success"});
            } else if (value.length > 0) {
                this.setData({recipientNameIconType: "error"});
            }else {
                this.setData({recipientNameIconType: ""});
            }
        }else if(id == "contactNumber"){
            value = value.substr(0, 11);
            this.setData({contactNumber: value});
            if(value==''){
                this.setData({urgentLinkTelIconType: "success"});
            }else if (FormCheckRule.telRule.test(value)) {
                this.setData({urgentLinkTelIconType: "success"});
            } else if (value.length > 0) {
                this.setData({urgentLinkTelIconType: "error"});
            } else {
                this.setData({urgentLinkTelIconType: ""});
            }

        }else if(id == "address.street"){
            this.setData({"address.street": value});
            if(value==''){
                this.setData({streetNameIconType: "success"});
            }else if(value.length>4){
                this.setData({streetNameIconType: "success"});
            } else if(value.length>0){
                this.setData({streetNameIconType: "error"})
            }else {
                this.setData({streetNameIconType: ""})
            }
        }

    },

    //是否勾选
    checkTap:function (e) {
        var needInvoice = e.target.dataset.agree;
        if(needInvoice==0){
            needInvoice = 1;
        }else{
            needInvoice = 0;
        }
        this.setData({needInvoice: needInvoice});
    },
    //车牌号码只能输入大写
    infoProFix: function(e){
        var pattern = /([^A-Za-z0-9]|\s)*/g,
            target = e.detail,
            that=this;
        if(target.value.length<=6){
            setTimeout(function(){
                that.setData({
                    cardFix: target.value.replace(pattern, "").replace("I", 1).replace("O", 0).toUpperCase()
                });
            },0);
        }

        if(target.value.length<6&&target.value.length!=0){
            if(target.value.length==1){
                if(!isNaN(target.value)){
                    that.setData({cardNbrIconType: "error"});
                    return false;
                }else {
                    that.setData({cardNbrIconType: "success"});
                    return false;
                }
            }
            if(FormCheckRule.carNbrSufRule.test(target.value)){
                that.setData({cardNbrIconType: "success"});
                return false;
            }else {
                that.setData({cardNbrIconType: "error"});
                return false;
            }
        }else {
            if(!isNaN(target.value)&&target.value!=''){
                that.setData({cardNbrIconType: "error"});
            }else {
                that.setData({cardNbrIconType: "success"});
            }
        }

    },

    //显示车辆类型列表
    typeSelection: function(e){
        var that = this;
        setTimeout(function(){
            that.setData({
                isCanScroll:false,
                showViewList: true,
                isShowFootNav: false
            });
        },100)
    },

    hideSelection: function(){
        this.setData({
            isCanScroll:true,
            showViewList: false,
            isShowFootNav: true
        });
    },

    //选择车辆类型列表
    showViewList: function(e){
        this.setData({
            isCanScroll:true,
            showViewList: false,
            typeStyle: "",
            typeSelectionText: e.target.dataset.name,
            typeSelectionCode: e.target.dataset.code,
            isShowFootNav: true
        });
    },
    //选择城市取消按钮
    cancelAddressTap:function (e) {
        this.setData({
            isAddressShow: false,
            isShowFootNav: true
        });
    },
    //选择城市确定按钮
    confirmAddressTap:function (e) {
        var current_value = this.data.value;
        var provinceName = this.data.proviceData[current_value[0]].name;
        var cityName = this.data.cityData[current_value[1]].name;
        var countyName = "";
        if(this.data.districtData[current_value[2]].name!=null){
            countyName = this.data.districtData[current_value[2]].name;
        }
        this.setData({
            isShowFootNav:true,
            isAddressShow: false,
            areaStyle:"color:#1a1a1a;font-size:34rpx",
            area:provinceName+cityName+countyName,
            "address.provinceId":this.data.proviceData[current_value[0]].id,
            "address.cityId":this.data.cityData[current_value[1]].id,
            "address.countyId":this.data.districtData[current_value[2]].id,
            "address.provinceName":provinceName,
            "address.cityName":cityName,
            "address.countyName":countyName
        });
    },
    //省市区滑动事件
    bindAddressChange: function (e) {
        app.bindAddressChange(e);
    }

});
